<template>
  <Input
      readonly
      :style="{ width }"
      :placeholder="'请选择'"
      v-model:value="iDisplayValue"
      @click="goSearchModal"
  >
  </Input>

  <Input
      style="display: none"
      :style="{ width }"
      :placeholder="'请选择'"
      v-model:value="currentSelect"
      @click="goSearchModal"
  >
  </Input>
  <AnnoSearchModal @register="registerSearchModal" @success="addRows">

  </AnnoSearchModal>
</template>
<script lang="ts" setup>
import {ref, watch, watchEffect} from 'vue';
import {Input} from 'ant-design-vue';
import AnnoSearchModal from "./AnnoSearchModal.vue";
import {useModal} from "@/components/Modal";
import {transOne} from "@/api/sys/anno";

const [registerSearchModal, {openModal: openSearchModal}] = useModal();
const trans = ref(true);
const addRows = (rows: any[]) => {
  if (rows.length > 0) {
    currentSelect.value = rows[0][props.valueKey];
    iDisplayValue.value = rows[0][props.labelKey];
    trans.value = false;
  }
};

function goSearchModal() {
  openSearchModal(true, {
    props,
    annoClassName: props.annoClass,
    isAdd: false,
  });
}

export interface Props {
  value?: string;
  displayValue?: string;
  labelKey: 'name',
  valueKey: 'id',
  annoClass?: string;
  width?: string;
}

const props = withDefaults(defineProps<Props>(), {
  displayValue: '',
  value: '',
  width: '100%',
  annoClass: 'AnUser'
});

// Don't inherit FormItem disabled、placeholder...
defineOptions({
  inheritAttrs: false,
});

const emit = defineEmits(['change', 'update:value']);


const currentSelect = ref('');
const iDisplayValue = ref('');

watchEffect(() => {
  currentSelect.value = props.value;
});

watch(
    () => currentSelect.value,
    (v) => {
      if (!v) {
        iDisplayValue.value = '';
      } else if (trans.value) {
        transOne({
          annoClazz: props.annoClass,
          idKey: props.valueKey,
          idValue: v,
          labelKey: props.labelKey
        }).then(
            res => {
              iDisplayValue.value = String(res);
            }
        );
      }
      trans.value = true;
      emit('update:value', v);
      emit('change', v);
    },
);
</script>
